package club.banyuan.demo.sec.service;

import club.banyuan.demo.sec.config.security.MyUserDetails;
import club.banyuan.demo.sec.dao.AuthDao;
import club.banyuan.demo.sec.model.Permission;
import club.banyuan.demo.sec.model.Role;
import club.banyuan.demo.sec.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private AuthDao authDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = authDao.findUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("未找到用户信息 : " + username);
        }

        List<Role> roles = authDao.findRolesByUserId(user.getId());

        List<Integer> roleIds = roles.stream()
                .map(Role::getId)
                .collect(Collectors.toList());

        List<Permission> permissions = authDao.findPermissionsByRoleIds(roleIds);

        return MyUserDetails.create(user, roles, permissions);
    }

}
